package cn.me.alphamq.client.consumer;

import cn.me.alphamq.client.cache.Container;
import cn.me.alphamq.common.entity.req.CreateTopicReq;
import cn.me.alphamq.common.entity.resp.CreateTopicResp;
import cn.me.alphamq.common.enumeration.EventCodeEnum;
import cn.me.alphamq.common.event.EventBus;
import cn.me.alphamq.common.remote.BrokerRespHandler;
import cn.me.alphamq.common.remote.NettyClient;
import com.alibaba.fastjson2.JSON;

import java.util.Scanner;

/**
 * 创建 topic 的控制台程序
 *
 * @author f
 */
public class TopicCreationConsole {

    public static void main(String[] args) {
        // 与 broker 建立连接
        Container.loadListeners();
        NettyClient client = new NettyClient(args[0]);
        client.initConnection("topic-creation-client",
                new BrokerRespHandler(new EventBus("topic-creation-client-event-bus")));

        // 获取需要创建的 topic 的 名称 和 队列数
        System.out.print("Please enter topic name: ");
        Scanner scanner = new Scanner(System.in);
        String topicName = scanner.next();
        System.out.print("Please enter queue size(1~32): ");
        int queueSize = scanner.nextInt();

        // 创建消息并发送
        byte[] body = client.sendMsgSync(EventCodeEnum.CREATE_TOPIC_REQ,
                new CreateTopicReq(topicName, queueSize)).getBody();

        // 处理结果
        CreateTopicResp createTopicResp = JSON.parseObject(body, CreateTopicResp.class);
        if (createTopicResp.getSuccess()) {
            System.out.println("创建成功");
        } else {
            System.out.println("创建失败，原因是：" + createTopicResp.getMsg());
        }

        // 断开连接，关闭程序
        client.close();
        System.exit(0);
    }
}
